<script setup>
import { ref, onMounted } from 'vue'
import { showLoadingToast, showSuccessToast, showFailToast, closeToast } from 'vant'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const couponList = ref([])
const loading = ref(true)
let isRequesting = false

// 加载优惠券列表
const loadCoupons = async () => {
  try {
    showLoadingToast({ message: '加载中...', forbidClick: true })
    const res = await userStore.fetchCoupons()
    couponList.value = res.data.map(item => ({
      ...item,
      remaining: item.total - item.received
    }))
  } catch (e) {
    showFailToast('加载失败')
  } finally {
    loading.value = false
    closeToast()
  }
}

// 领取优惠券带防抖
const handleGetCoupon = async (id) => {
  if (isRequesting) return
  isRequesting = true
  
  try {
    showLoadingToast({ message: '领取中...', forbidClick: true })
    await userStore.getCoupon(id)
    
    // 更新本地剩余数量
    const index = couponList.value.findIndex(item => item.id === id)
    if (index > -1) {
      couponList.value[index].remaining -= 1
    }
    
    showSuccessToast('领取成功')
  } catch (e) {
    showFailToast(e.code === 4001 ? '库存不足' : '领取失败')
  } finally {
    isRequesting = false
    closeToast()
  }
}

onMounted(loadCoupons)
</script>

<template>
  <div class="coupon-center">
    <van-skeleton title :row="3" :loading="loading">
      <div v-for="coupon in couponList" :key="coupon.id" class="coupon-item">
        <!-- 优惠券模板 -->
        <van-button 
          type="primary"
          :disabled="coupon.remaining <= 0"
          @click="handleGetCoupon(coupon.id)"
        >
          {{ coupon.remaining > 0 ? '立即领取' : '已领完' }}
        </van-button>
      </div>
    </van-skeleton>
  </div>
</template>